package hikari.persistence.handlersimpl;

import com.gooddies.wiring.annotations.WiringComponent;
import hikari.objects3d.Basic3dObject;
import hikari.objects3d.NavMesh3dObject;
import hikari.persistence.file.FileSection;
import hikari.persistence.persisthandlers.IPersistantObject3dReadHandler;
import hikari.persistence.persisthandlers.PersistantHandler;
import java.io.IOException;
import org.swig.jirr.ISceneManager;
import org.swig.jirr.S3DVertex;
import org.swig.jirr.SColor;
import org.swig.jirr.vector2df;
import org.swig.jirr.vector3df;

/**
 * @author Dmitry
 */
@WiringComponent(singleton = true, lazy = true)
@PersistantHandler(sectionName = "navmeshSettings")
public class NavmeshParametersLoadHandler implements IPersistantObject3dReadHandler {
    private NavmeshParametersLoadHandler() {
    }

    private int[] convertToLongArray(long[] array) {
        int[] newArray = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            newArray[i] = (int) array[i];
        }

        return newArray;
    }

    @Override
    public Basic3dObject read(ISceneManager sceneManager, Basic3dObject object, FileSection section) throws IOException {
        NavMesh3dObject navmesh = (NavMesh3dObject) object;
        vector3df[] verticesPositions = section.readVectors("vertices");
        long[] indiciesLong = section.readLongs("indicies");
        int[] indicies = convertToLongArray(indiciesLong);
        navmesh.getMeshSceneNode().setIndices(indicies);
        S3DVertex[] vertices = new S3DVertex[verticesPositions.length];
        for (int i = 0; i < vertices.length; i++) {
            vertices[i] = new S3DVertex(verticesPositions[i], verticesPositions[i], SColor.BLUE_L, new vector2df(0, 0));
        }
        navmesh.getMeshSceneNode().setVertices(vertices);
        navmesh.getMeshSceneNode().recalculate();
        navmesh.getMeshSceneNode().getMaterial(0).setBackfaceCulling(false);
        return object;
    }
}
